#! /bin/bash

check_process_exists() {
    local process_name="$1"
    if ps aux | grep -v grep | grep "$process_name" > /dev/null; then
        return 0  # 进程存在，返回 0
    else
        return 1  # 进程不存在，返回 1
    fi
}

check_and_sleep() {
    local process_name="$1"
    #local pid=$(pgrep -f "$process_name")
    #echo "pid $pid"
    local cnt=0
    while true; do
        cnt=`expr $cnt + 1`
        #local npid=$(pgrep -f "$process_name")
        #echo "npid $npid"
        if ps aux | grep -v grep | grep "$process_name" > /dev/null; then
            #if ["$pid" == "$npid"];then
                echo "Process $process_name is running. Sleeping for $cnt second..."
                sleep 1
            #else
               # echo "Process $process_name is not running. Exiting..."
               # return
            #fi
        else
            echo "Process $process_name is not running. Exiting..."
            return
        fi
    done
}

kill_process_by_name() {
    local process_name="$1"
    local pid=$(pgrep -f "$process_name")
    if [ -n "$pid" ]; then
        kill -15 "$pid"
        echo "Process $pid ($process_name) terminated."
    else
        echo "Process $process_name not found."
    fi
}

start_process(){
  local process_name="$1"
  echo "start $process_name !!!"
  chmod 777 $process_name
  nohup ./$process_name ->logs/log.out 2>&1 &
}

# 要监听的进程名称
process_name=tapay-ws
if check_process_exists "$process_name"; then
    echo "Process $process_name exists."
    kill_process_by_name "$process_name"
    check_and_sleep "$process_name"
    start_process $process_name
else
    echo "Process $process_name does not exist."
    start_process $process_name
fi
